<?php
include("../includes/common.php");

$title = '文件查看 - '.$conf['title'];
$is_file=true;
if($conf['forcelogin']==1 && !$islogin2) {loginsmsg('请登录后再操作！');}
include './head.php';
$csrf_token = md5(mt_rand(0,999).time());
$_SESSION['csrf_token'] = $csrf_token;

$hash = isset($_GET['hash'])?$_GET['hash']:exit("<script language='javascript'>window.location.href='./';</script>");
$pwd = isset($_GET['pwd'])?$_GET['pwd']:null;
$row = $DB->getRow("SELECT * FROM pre_file WHERE hash=:hash", [':hash'=>$hash]);
if(!$row)exit("<script language='javascript'>alert('文件不存在');window.location.href='./';</script>");
$name = $row['name'];
$type = $row['type'];

$downurl = 'down.php/'.$row['hash'].'.'.$type;
if(!empty($row['pwd']))$downurl .= '&'.$row['pwd'];
$viewurl = 'view.php/'.$row['hash'].'.'.$type;

$downurl_all = $siteurl.$downurl;
$viewurl_all = $siteurl.$viewurl;
// 保持原始本站链接显示，同时按文件存储类型补充云直链（不替换原链接）
$storageType = $row['storage'] ?: $conf['storage'];
$stor = \lib\StorHelper::getModel($storageType);
$isCloud = in_array($storageType, ['oss','qcloud','obs','upyun','qiniu']);
$cloud_viewurl = null;
$cloud_downurl = null;
if($isCloud && $conf['downfile_type'] == 1){
  $cloudView = $stor->getDownUrl($hash, $name, minetype($type));
  if($cloudView) $cloud_viewurl = $cloudView;
  $cloudDown = $stor->getDownUrl($hash, $name, null);
  if($cloudDown) $cloud_downurl = $cloudDown;
}
// 是否启用云直链（按文件自身存储与开关），仅用于补充展示，不替换本站链接
$is_cloud_direct = $isCloud && $conf['downfile_type'] == 1 && (!empty($cloud_viewurl) || !empty($cloud_downurl));

if($islogin2 && $row['uid']==$uid || !$islogin2 && isset($_SESSION['fileids']) && in_array($row['id'], $_SESSION['fileids']) && strtotime($row['addtime'])>strtotime("-7 days")){
  $is_mine = true;
}

$view_type = get_view_type($type);

if($view_type == 'image'){
  $filetype = 1;
  $title = '<i class="fa fa-picture-o"></i> 图片查看器';
  $htmlcode = htmlspecialchars('<img src="'.($is_cloud_direct?$viewurl_all:$viewurl_all).'"/>');
  $ubbcode = '[img]'.($is_cloud_direct?$viewurl_all:$viewurl_all).'[/img]';
  if($is_cloud_direct && !empty($cloud_viewurl)){
    $htmlcode_cloud = htmlspecialchars('<img src="'.$cloud_viewurl.'"/>');
    $ubbcode_cloud = '[img]'.$cloud_viewurl.'[/img]';
  }
  $linktitle = '图片链接';
}elseif($view_type == 'audio'){
  $filetype = 2;
  $title = '<i class="fa fa-music"></i> 音乐播放器';
  $htmlcode = htmlspecialchars('<audio id="bgmMusic" src="'.$viewurl_all.'" autoplay="autoplay" loop="loop" preload="auto"></audio>');
  $htmlcode2 = htmlspecialchars('<iframe src="'.$siteurl.'player.php?hash='.$hash.'" width="407" scrolling="no"frameborder="0"height="70"></iframe>');
  $ubbcode = '[audio=X]'.$viewurl_all.'[/audio]';
  if($is_cloud_direct && !empty($cloud_viewurl)){
    $htmlcode_cloud = htmlspecialchars('<audio id="bgmMusic" src="'.$cloud_viewurl.'" autoplay="autoplay" loop="loop" preload="auto"></audio>');
    $ubbcode_cloud = '[audio=X]'.$cloud_viewurl.'[/audio]';
  }
  $linktitle = '音乐链接';
}elseif($view_type == 'video'){
  $filetype = 3;
  $title = '<i class="fa fa-video-camera"></i> 视频播放器';
  $htmlcode = htmlspecialchars('<video id="movies" src="'.$viewurl_all.'" autobuffer="true" controls="" width="100%"></video>');
  $htmlcode2 = htmlspecialchars('<iframe src="'.$siteurl.'player.php?hash='.$hash.'" width="800" height="500" scrolling="no" frameborder="0"></iframe>');
  $ubbcode = '[movie=320*180]'.$viewurl_all.'[/movie]';
  if($is_cloud_direct && !empty($cloud_viewurl)){
    $htmlcode_cloud = htmlspecialchars('<video id="movies" src="'.$cloud_viewurl.'" autobuffer="true" controls="" width="100%"></video>');
    $ubbcode_cloud = '[movie=320*180]'.$cloud_viewurl.'[/movie]';
  }
  $linktitle = '视频链接';
}else{
  $filetype = 0;
  $title = '<i class="fa fa-file"></i> 文件查看';
  $htmlcode = htmlspecialchars('<a href="'.$downurl_all.'" target="_blank">'.$name.'</a>');
  $ubbcode = '[url='.$downurl_all.']'.$name.'[/url]';
  if($view_type == 'office'){
    $office_url = 'https://view.officeapps.live.com/op/view.aspx?src='.rawurlencode($downurl_all);
  }
}
?>

<div class="layui-fluid">
  <div class="layui-row layui-col-space15">
    <div class="layui-col-md8 layui-col-sm12">
      <div class="layui-card">
        <div class="layui-card-header">文件预览</div>
        <div class="layui-card-body">
          <div class="layui-row">
            <div class="layui-col-md12">
              <div class="preview">
                <?php if($view_type=='image'){ ?>
                  <img src="<?php echo $viewurl_all?>" alt="<?php echo htmlspecialchars($name)?>" style="max-width:100%;height:auto;border-radius:6px" />
                <?php }elseif($view_type=='audio'){ ?>
                  <audio controls preload="auto" style="width:100%"><source src="<?php echo $viewurl_all?>"></audio>
                <?php }elseif($view_type=='video'){ ?>
                  <video controls style="width:100%"><source src="<?php echo $viewurl_all?>"></video>
                <?php }else{ ?>
                  <div style="padding:40px;text-align:center">
                    <i class="layui-icon layui-icon-file" style="font-size:48px;color:#999"></i>
                    <div style="margin-top:12px;font-size:16px">文件：<?php echo htmlspecialchars($name)?></div>
                    <div style="color:#777;margin-top:6px">使用下方链接预览或下载</div>
                  </div>
                <?php } ?>
              </div>
            </div>
          </div>

          <div style="margin-top:14px">
            <div class="layui-card">
              <div class="layui-card-header">嵌入 / 分享</div>
              <div class="layui-card-body">
                <div class="layui-form-item">
                  <label class="layui-form-label">站内嵌入</label>
                  <div class="layui-input-block code"><?php echo $htmlcode?></div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">UBB</label>
                  <div class="layui-input-block code"><?php echo $ubbcode?></div>
                </div>
                <?php if(!empty($htmlcode_cloud)){ ?>
                <div class="layui-form-item">
                  <label class="layui-form-label">云直链（可选）</label>
                  <div class="layui-input-block code"><?php echo $htmlcode_cloud?></div>
                </div>
                <?php } ?>
              </div>
            </div>
          </div>

        </div>
      </div>

    </div>

    <div class="layui-col-md4 layui-col-sm12">
      <div class="layui-card">
        <div class="layui-card-header">文件信息</div>
        <div class="layui-card-body">
          <p><strong>文件名</strong><br><?php echo htmlspecialchars($name)?></p>
          <p><strong>类型</strong><br><?php echo $type?></p>
          <p><strong>大小</strong><br><?php echo round($row['size']/1024/1024,2)?> MB</p>
          <p><strong>存储</strong><br><?php echo $storageType?></p>
          <?php if(isset($office_url)){ ?>
            <p><strong>Office 在线预览</strong><br><a href="<?php echo $office_url?>" target="_blank">打开</a></p>
          <?php } ?>
        </div>
      </div>

      <div class="layui-card" style="margin-top:12px">
        <div class="layui-card-header">链接信息</div>
        <div class="layui-card-body">
          <div style="margin-bottom:10px">
            <div class="layui-row layui-col-space5">
              <div class="layui-col-xs9">
                <div class="code">查看链接：<?php echo $viewurl_all?></div>
              </div>
              <div class="layui-col-xs3">
                <button class="layui-btn layui-btn-sm layui-block" onclick="copyText('<?php echo $viewurl_all?>')">复制</button>
              </div>
            </div>
          </div>

          <div style="margin-bottom:10px">
            <div class="layui-row layui-col-space5">
              <div class="layui-col-xs9">
                <div class="code">下载链接：<?php echo $downurl_all?></div>
              </div>
              <div class="layui-col-xs3">
                <button class="layui-btn layui-btn-sm layui-block" onclick="copyText('<?php echo $downurl_all?>')">复制</button>
              </div>
            </div>
          </div>

          <?php if(!empty($cloud_viewurl)){ ?>
          <div style="margin-bottom:10px">
            <div class="layui-row layui-col-space5">
              <div class="layui-col-xs9">
                <div class="code">云直链：<?php echo $cloud_viewurl?></div>
              </div>
              <div class="layui-col-xs3">
                <button class="layui-btn layui-btn-sm layui-block" onclick="copyText('<?php echo $cloud_viewurl?>')">复制</button>
              </div>
            </div>
          </div>
          <?php } ?>

          <div>
            <button class="layui-btn layui-btn-warm layui-block" onclick="copyAll()">复制全部链接</button>
          </div>
        </div>
      </div>

      <div style="margin-top:12px" class="layui-card">
        <div class="layui-card-header">操作</div>
        <div class="layui-card-body">
          <div class="layui-row layui-col-space10">
            <?php if($is_mine){ ?>
            <div class="layui-col-xs12" style="margin-bottom:8px">
              <button class="layui-btn layui-btn-danger layui-block" onclick="if(confirm('确定删除此文件？')) location.href='?hash=<?php echo $hash?>&delete=1'">删除</button>
            </div>
            <?php } ?>
          </div>
        </div>
      </div>

    </div>
  </div>
</div>

<script>
// 复制函数：使用 layui layer 提示
if(typeof layui !== 'undefined' && layui.layer){ window.layer = layui.layer; }
function copyText(t){
  try{
    navigator.clipboard.writeText(t).then(function(){ if(window.layer) layer.msg('已复制到剪贴板'); else alert('已复制'); });
  }catch(e){
    try{ var ipt=document.createElement('textarea'); ipt.value=t; document.body.appendChild(ipt); ipt.select(); document.execCommand('copy'); document.body.removeChild(ipt); if(window.layer) layer.msg('已复制到剪贴板'); else alert('已复制'); }catch(ex){ alert('复制失败，请手动复制'); }
  }
}
function copyAll(){
  var list = [];
  list.push('<?php echo $viewurl_all?>');
  list.push('<?php echo $downurl_all?>');
  <?php if(!empty($cloud_viewurl)){ ?>list.push('<?php echo $cloud_viewurl?>');<?php } ?>
  var joined = list.join('\n');
  try{ navigator.clipboard.writeText(joined).then(function(){ if(window.layer) layer.msg('已复制全部链接到剪贴板'); else alert('已复制全部链接'); }); }catch(e){ try{ var ipt=document.createElement('textarea'); ipt.value=joined; document.body.appendChild(ipt); ipt.select(); document.execCommand('copy'); document.body.removeChild(ipt); if(window.layer) layer.msg('已复制全部链接到剪贴板'); else alert('已复制全部链接'); }catch(ex){ alert('复制失败，请手动复制'); } }
}
</script>

<?php include 'foot.php';?>
